'use strict'
import {
  Model,
  DataTypes,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
} from 'sequelize'
import dayjs from 'dayjs'
import { Models } from '../type'
import sequelize from './index'

class Attachment extends Model<InferAttributes<Attachment>, InferCreationAttributes<Attachment>> {
  declare id: CreationOptional<number>
  declare userId: number
  declare originalname: string
  declare filename: string
  declare mimetype: string
  declare size: number
  declare path: string
  declare fullpath: string
  declare url: string
  declare createdAt: CreationOptional<Date>
  declare updatedAt: CreationOptional<Date>

  static associate(models: Models) {
    Attachment.belongsTo(models.User, { as: 'user', foreignKey: 'userId' })
  }
}
Attachment.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    userId: DataTypes.INTEGER,
    originalname: DataTypes.STRING,
    filename: DataTypes.STRING,
    mimetype: DataTypes.STRING,
    size: DataTypes.INTEGER,
    path: DataTypes.STRING,
    fullpath: DataTypes.STRING,
    url: DataTypes.STRING,
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('createdAt')
          ? dayjs(this.getDataValue('createdAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('updatedAt')
          ? dayjs(this.getDataValue('updatedAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
  },
  {
    sequelize,
    modelName: 'Attachment',
  },
)

export default Attachment
